package com.aisino.mplearning;

/**
 * @author guochuantao
 * @version 1.0
 * @description
 * @since 2024/9/9 下午3:23
 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class DatabaseFieldLength {
    public static void main(String[] args) {
        String url = "jdbc:mysql://172.19.12.222:3306/dyw_test01?useUnicode=true&characterEncoding=utf8&nullCatalogMeansCurrent=true"; // 替换为你的数据库URL
        String user = "root"; // 替换为你的数据库用户名
        String password = "sjzl@2024"; // 替换为你的数据库密码
        String tableName = "xxl_job_log"; // 替换为你想要查询的表名

        Connection conn = null;
        try {
            // 1. 加载JDBC驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. 建立数据库连接
            conn = DriverManager.getConnection(url, user, password);

            // 3. 执行查询获取表的数据
            String query = "SELECT * FROM " + tableName;
            try (Statement stmt = conn.createStatement();
                 ResultSet rs = stmt.executeQuery(query)) {

                // 4. 获取结果集元数据
                ResultSetMetaData metaData = rs.getMetaData();

                // 5. 获取列的数量
                int columnCount = metaData.getColumnCount();

                // 6. 获取字段长度
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    int columnDisplaySize = metaData.getColumnDisplaySize(i);
                    System.out.println("Column Name: " + columnName + ", Display Size: " + columnDisplaySize);
                }
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
